//
//  ZJNetWork.swift
//  mini
//
//  Created by Mac on 2017/5/22.
//  Copyright © 2017年 Mac. All rights reserved.
//

import UIKit
import Alamofire

let host = "https://weixin.yk2020.com/"

enum resultFormat {
    case json
    case string
}

struct requestRecource<T> {
    
    let path : String
    let params:[String:Any]
    let parser : (Any) -> T?
    
}

extension requestRecource {

    
    @discardableResult
    func request (type:HTTPMethod = .post,result:resultFormat = .json,callback:@escaping (T?)->Void,failed:@escaping(Error?)->Void ) -> requestRecource{
        let fullUrl = host + path
        
        //获取sessionManger 方便设置
        let sessionManger = Alamofire.SessionManager.default
        sessionManger.request(fullUrl, method: type, parameters: params, encoding: JSONEncoding())
            .validate()
            .responseJSON { (jsonResult) in
                if result == .json{
                    switch jsonResult.result {
                        
                    case .success(let json):
                        callback(self.parser(json))
                    case .failure(let error):
                        failed(error)
                    }
                    
                }
            }.responseString{ StringResult in
                if result == .string{
                    switch StringResult.result {
                    case .success(let string):
                        callback(self.parser(string))
                    case .failure(let error):
                        failed(error)
                    }
                }
        }
        return self
        
    }
    
}
